﻿$(function () {
    $.datepicker.setDefaults($.datepicker.regional["th"]);
});

function mslLookupFor(searchValue) {
	var res = $.ajax({
        url: "_findmsl.php?v=" + $.now(),
        type: 'GET',
        data: 'Search=' + searchValue,
        success: function (result) {
            if (result == "Notfound") {
                alert("ไม่พบสมาชิก!");
                $("#DIST").val(""); 
				$("#MSLNO").val("");
				$("#CHKDGT").val("");
				$("#MSLNAME").val("");
                $("#DIST").focus();
            }
            else {
                $("#MSLNAME").val(result);
            }
        },
        fail: function (result) {
            $("#DIST").val(""); 
			$("#MSLNO").val("");
			$("#CHKDGT").val("");
        }
    });
}

function billCodeLookupFor(obj) {
	var maxCamp = $("#MAXCAMP").val();
	var minCamp = $("#MINCAMP").val();
	var billcode = $(obj).val();
    
    $.ajax({
        url: "_findbillcode.php?v=" + $.now(),
        type: 'GET',
        data: 'Search=' + billcode + '&Max=' + maxCamp + '&Min=' + minCamp,
        success: function (result) {
            if (result == "Notfound") {
                alert("ไม่พบสินค้าที่ระบุ!");
                clearForm();
                $("#BILLCODE").focus();
            }
            else {
            	var _binding = result.split("|");
            	if (_binding.length > 1)
            	{
	                $("#QTY").focus();
            		if (_binding[4] != "")
            		{
						alert(_binding[4]);
					}
					
	                $("#BILLCODE").val(_binding[0]);
	                $("#BILLDESC").val(_binding[1]);
	                $("#PRICE").val(addCommas(_binding[2]));
	                $("#ORDCAMPD").val(_binding[3]);
	                $("#AMOUNT").val(addCommas(calculateAmount()));
				}
				else
				{
					alert(result);
				}
            }
        },
        fail: function (result) {
            $(obj).val("");
        }
    });
}

function validateNumber(e,obj) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;   
    if (charCode > 31 && 
    		(charCode < 46 || charCode > 57) && 
    		(charCode < 96 || charCode > 105) || charCode == 9) {
        return false;
    }
	
    if (charCode == 13)
    {
		if ($(obj).attr('id') == "BILLCODE")
		{
			if (checkEmpty(obj))
			{
				billCodeLookupFor(obj);
				getResponseTime();
			}				
		} 
		else if ($(obj).attr('id') == "QTY")
		{
			if (checkEmpty($("#BILLCODE")) && checkEmpty($("#BILLDESC")) && checkEmpty(obj))
			{				
				$("#AMOUNT").val(addCommas(calculateAmount()));
				doCommand("Add");
                clearForm();
				$("#BILLCODE").focus();	
				getResponseTime();
			}
		}
	}
    /*else if ($(obj).val().length == 5 && charCode != 8 && charCode != 46)
    {    	
    	billCodeLookupFor(obj);
    	getSummary();  
    	//alert(charCode);
    	//$("#QTY").val(String.fromCharCode(charCode));
	}*/
    return true;
}

function validateLogin(e,obj) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
    if (charCode == 9) {
        return false;
    }

    if (charCode == 13)
    {
		if ($(obj).attr('id') == "RACCOUNT_ID")
		{
			if ($(obj).val() == "")
			{
				alert("กรุณากรอก Username");
				return false;
			}
			$("#ACCOUNT_PASSWORD").focus();
		} 
		else if ($(obj).attr('id') == "ACCOUNT_PASSWORD")
		{
			if ($(obj).val() == "")
			{
				alert("กรุณากรอก Password");
				return false;
			}
			$("#RACCOUNT_ID").focus();					
		}
		
		if ($("#RACCOUNT_ID").val() != "" && $("#ACCOUNT_PASSWORD").val() != "")
		{
			$("#main-form").submit();
		}
	}
    return true;
}

function validateMember(e,obj) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
    if (charCode > 31 && 
    		(charCode < 46 || charCode > 57) && 
    		(charCode < 37 || charCode > 40) &&
    		(charCode < 96 || charCode > 105) || charCode == 9) {
        return false;
    }

    if (charCode == 13 || charCode == 0 || charCode == 1)
    {
		if ($(obj).val() == "")
		{
			alert('กรุณาระบุรหัสสมาชิกให้ครบถ้วน');
			changeFocus();
			return false;
		}
		else
		{			
			if ($(obj).attr('id') == "DIST")
			{
				$("#MSLNO").focus();
			} 
			else if ($(obj).attr('id') == "MSLNO")
			{
				$("#CHKDGT").focus();
			} 
			else if ($(obj).attr('id') == "CHKDGT")
			{
				var _dist = $("#DIST").val();
				var _mslno = $("#MSLNO").val();
				var _chkdgt = $("#CHKDGT").val();
				var _memberno = lpad(_dist, 4, 0) + lpad(_mslno, 5, 0) + _chkdgt;
				mslLookupFor(_memberno);
				$("#ORDCAMP").focus();				
				getResponseTime();
			} 
			else if ($(obj).attr('id') == "ORDCAMP")
			{
				checkMember();
			}
		}				
	}
    return true;
}

function doCommand(com, grid) {
    if (com == 'Delete') {
        var conf = confirm('ลบรายการที่เลือก ' + $('.trSelected', grid).length + ' รายการ?')
        if(conf){
            $.each($('.trSelected', grid),
                function(key, value){
                	//alert(value.firstChild.innerText);
                	$.get('_getorderDetail.php?v=' + $.now(), { 
                		Delete: value.firstChild.innerText
                	}, function(){
                        $(".flexme4").flexReload();
                        getSummary(); 
                	});
            });
        }
    	       
    }
    else if (com == 'Add') {
        var _billcode = $("#BILLCODE").val();
        var _qty = $("#QTY").val();
        var _billdesc = $("#BILLDESC").val();
        var _price = $("#PRICE").val();
        var _amount = $("#AMOUNT").val();
        var _ordcampd = $("#ORDCAMPD").val(); 
        	
        $.get('_getorderDetail.php?v=' + $.now(), { 
        	Add: true, 
        	BILLCODE: _billcode, 
        	QTY: _qty, 
        	BILLDESC: _billdesc, 
        	PRICE: _price, 
        	AMOUNT: _amount,
        	ORDCAMPD: _ordcampd
        }, function(){
			$(".flexme4").flexReload();
			getSummary();
        });    	
    }
}

function checkEmpty(obj){
    if ($(obj).attr("id") == "BILLCODE" && ($(obj).val() == "" || $(obj).val().length < 5)) {
        alert('กรุณาระบุรหัสสินค้าให้ครบถ้วน');
        $(obj).focus();
        return false;
    }
    else if ($(obj).attr("id") == "QTY" && ($(obj).val() == "" || $(obj).val() == 0)) {
        alert('กรุณาระบุจำนวนสินค้า');
        $(obj).val("");
        $(obj).focus();
        return false;				
    }
    else if ($(obj).attr("id") == "BILLDESC" && $.trim($(obj).val().length) < "1") {
        alert('กรุณากดปุ่ม Enter เพื่อตรวจสอบรหัสสินค้า');
        $("#BILLCODE").focus();
        return false;	
	}
	return true;
}

function clearForm(){
	$("#BILLCODE").val("");
	$("#QTY").val("");
	$("#BILLDESC").val("");
	$("#PRICE").val("");
	$("#ORDCAMPD").val("");
	$("#AMOUNT").val("");
	return true;
}

function getSummary(){
	//var dt = new Date();
	//var time = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds();
	//alert($.now());	
	$.ajax({
        url: "_sumtotal.php?v=" + $.now(),
        type: 'GET',
        success: function (result) {
        	//alert(result);
        	var _binding = result.split("|");
        	if (_binding.length > 1)
        	{      	
	            if (_binding[2].replace(/\,/g, "") > 0) 
	            {
	                $("#TOTAL").val(_binding[0]);
	                $("#ITEMS").val(_binding[1]); 
	                $("#LIST").val(_binding[2]);          
	            }
	            else
	            {
					$("#TOTAL").val("");
					$("#ITEMS").val("");
					$("#LIST").val("");								
				}		            
			}
            else
            {
				$("#TOTAL").val("");
				$("#ITEMS").val("");
				$("#LIST").val("");								
			}			
        },
        fail: function (result) {
			$("#TOTAL").val("");
			$("#ITEMS").val("");
			$("#LIST").val("");	
        }
    });      
}

function getCount(){
	$.ajax({
        url: "_countrow.php?v=" + $.now(),
        type: 'GET',
        success: function (result) {
			if (result == "FALSE")
			{
				alert('กรุณาระบุรายการสินค้า');
				$("#BILLCODE").focus();
				event.preventDefault ? event.preventDefault() : event.returnValue = false;
				return false;
			}
			else
			{
				$("#main-form").submit();
			}
        },
        fail: function (result) {
            return false;
        }
    });
}

function changeFocus(){
	if ($("#DIST").val() == "")
	{
		$("#DIST").focus();
	} 
	else if ($("#MSLNO").val() == "") 
	{
		$("#MSLNO").focus();
	} 
	else if ($("#CHKDGT").val() == "")
	{
		$("#CHKDGT").focus();
	}
}

function addCommas(str) {
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        i = len - 1;

    while (i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

function calculateAmount(){
	var _price = ($("#PRICE").val().replace(/\,/g, "")>0)? $("#PRICE").val().replace(/\,/g, "") : 0;
	var _qty = ($("#QTY").val().replace(/\,/g, "")>0)? $("#QTY").val().replace(/\,/g, "") : 0;
	var _amount = parseFloat(_price) * parseFloat(_qty);
	return _amount;
}

function lpad(input, pad_length, pad_string) {
    for (i = input.length; i < pad_length; i++) {
        input = pad_string + input;
    }
    return input;
}

function checkMember(){
	if ($("#DIST").val() == "" || 
		$("#MSLNO").val() == "" ||
		$("#CHKDGT").val() == "" ||
		$("#MSLNAME").val() == "")
		{
			alert('กรุณาระบุรหัสสมาชิกให้ครบถ้วน');
			changeFocus();				
			event.preventDefault ? event.preventDefault() : event.returnValue = false;
			return false;
		}
		else
		{				
			$("#main-form").submit();
		}	
}

function getResponseTime(){
	$.ajax({
        url: "_responsetime.php?v=" + $.now(),
        type: 'GET',
        success: function (result) {
        	window.status = result;		
        },
        fail: function (result) {
			window.status = 'err';
        }
    });
}